import axios from 'axios'
import { getToken } from './storage'
import { message } from 'antd'
import history from './history'
import { removeToken } from './storage'
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 请求配置的统一处理封装请求头
    const token = JSON.parse(getToken())
    if (token) {
      config.headers.Authorization = 'Bearer ' + token.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    // 响应失败
    if (error.response && error.response.status === 401) {
      removeToken()
      message.error('token过期')
      history.push('./login')
    }
    return Promise.reject(error)
  }
)

export default instance
